<template>
	<view style="height: 100%;">
        
            <view class="top" style="height: 8vh">
                <view class="label">
                    <image src="/static/images/location_select.png" @click="selectLocation"></image>
                    <!-- <image wx:if="{{total}}" src='/images/choice_y.png'></image>
    <image wx:else src='/images/choice_n.png'></image> -->
                </view>
                <text class="city" @click="selectLocation">{{ address }}</text>
                <text v-if="!isEdit" class="edit-btn" @click="editFun">编辑</text>
                <text v-else class="edit-btn" @click="editFun">完成</text>
				
            </view>
			<view style="height: 68vh">
            <scroll-view scroll-y class="list" style="height: 68vh">
                <view class="item" v-if="!isEdit" v-for="(item, index) in list" :key="index">
                    <view class="label" @click="labelFun(index,item)" :data-id="list.id">
                        <image :src="lableUrls[index].url"></image>
                        <!-- <image v-else src="/static/images/choice_n.png"></image> -->
                    </view>
                    <navigator class="content" hover-class="none" :url="'/pages/goodsdetail/goodsdetail?id=' + item.productID">
                        <image :src="'http://1.14.101.56:82/'+item.productImg"></image>
                        <view class="text">
                            <view class="title">{{ item.productName }}</view>
                            <view class="spec">{{ item.spec }}</view>
                            <view class="price">
                                <text>¥{{ item.price }}</text>
                                <text>x{{ item.num }}</text>
                            </view>
                        </view>
                    </navigator>
                </view>
                <view class="item edit" v-if="isEdit" v-for="(item, index) in list" :key="index">
                    <view class="label" @click="labelFun(index,item)">
						<span>{{item.labelFlag}}</span>
                        <image v-if="item.labelFlag" src="/static/images/choice_y.png"></image>
                        <image v-else src="/static/images/choice_n.png"></image>
                    </view>

                    <view class="content">
                        <image :src="'http://1.14.101.56:82/'+item.productImg"></image>
                        <view class="text">
                            <view class="title">
                                <text :class="item.num == 1 ? 'prohibit' : '' "  @click="reduceFun(item.productID,item.num)" :data-item="item">-</text>
                                <input @input="bindNum" @blur="bindblur" type="number" :data-item="item" :value="item.num" />
                                <text @click="plusFun(item.productID,item.num)" :data-item="item">+</text>
                            </view>
                            <view class="spec">{{ item.spec }}</view>
                            <view class="price">
                                <text>¥{{ item.price }}</text>
                            </view>
                        </view>
                    </view>

                    <view class="del-btn" @click="delItemFun(item.productID)" :data-item="item">删除</view>
                </view>
            </scroll-view>
			</view>
            <view class="bottom" style="height: 10vh">
                <view class="left">
                    <view class="text">
                        <view class="label" style="padding-left: 16px" @click="totalFun">
                            <image v-if="total" src="/static/images/choice_y.png"></image>
                            <image v-else src="/static/images/choice_n.png"></image>
                        </view>
                        <text @click="totalFun" style="padding-left: 10px">全选</text>
                    </view>
                    <view class="total-price" v-if="!isEdit">
                        合计:
                        <text style="color: red; margin-right: 10px">￥{{ totalPrice }}</text>
                        <view style="font-size: 10px; margin-right: 10px">不含运费</view>
                    </view>
                </view>
                <view :class="totalPrice > 0 ? 'right' : 'right prohibit'" @tap="closeFun(list)" v-if="!isEdit">结算</view>
                <view :class="totalPrice > 0 ? 'right' : 'right prohibit'" @tap="delFun" v-if="isEdit">删除</view>
            </view>
       
		</view>
</template>

<script>
const app = getApp();

let select_list = [];
let changeNum = 0;
export default {
    data() {
        return {
			lableUrls: [],
            total: false,
            //是否全选
            totalPrice: 0,
            //总价
            list: [],
            isEdit: false,
            address: '',
            userName: '',
            mobilePhone: 0,
            addressDetail: '',
        };
    },
    onShow: function (options) {
		let userid=uni.getStorageSync("userid");
        // console.log(options+"2")
        if (app.globalData.address == null) {
            uni.request({
				url:"/api/user/address/getAddress",
				method:"POST",
				data:{user_id:userid},
                    success: (res) => {
						console.log(res.data.addressList[0]);
                        this.setData({
                            address: res.data.addressList[0].province+res.data.addressList[0].city+res.data.addressList[0].district,
                            mobilePhone: res.data.addressList[0].phone_number,
                            userName: res.data.addressList[0].real_name
                        }); // console.log(this.data.userName)
                    }
                });
        } else {
            // console.log(app.globalData.address)
            this.setData({
                address: app.globalData.address,
                addressDetail: app.globalData.addressDetail,
                mobilePhone: app.globalData.phone_number,
                userName: app.globalData.real_name
            }); // console.log(this.data.mobilePhone)
        }
    },
    onLoad: function (options) {
		
        let userid=uni.getStorageSync("userid");
         // console.log(app.globalData.addressDetail);
         var that = this;
        uni.request({
        				url:"/api/user/shoppingCart/getShoppingCart",
        				method:"POST",
        				data:{user_id:userid},
        				success(res) {
                 // console.log("查询成功",res)
                 that.list= res.data.shoppingCartData
				 that.list.forEach(item => {
					 that.lableUrls.push({url:"/static/images/choice_n.png"})
				 })
                  console.log("查询成功", res.data.shoppingCartData)
             },
        
             fail: (res) => {
                 console.log('查询失败', res);
             }
        })
    },
    methods: {
        bindNum: function (event) {
            changeNum = event.detail.value;
        },

        bindblur: function (e) {
			let userid=uni.getStorageSync("userid");
            var id = e.target.dataset.item.id;

            if (parseInt(changeNum) == 0) {
                uni.showToast({
                    title: '该宝贝不能再减少了哦~',
                    icon: 'none',
                    duration: 2000
                });
            } else {
                uni.request({
                	url:"/api/user/shoppingCart/updateShoppingCart",
					method:"POST",
                data: {
                    num: parseInt(changeNum),
					user_id:userid,
					product_id:product_id
                },
                success: (res) => {
                    console.log('更新成功', res);
                },
                fail: (res) => {
                    console.log('更新失败', res);
                }
      
                    });
            }
        },

        selectLocation: function (e) {
            //选中地址
            uni.navigateTo({
                url: '/pages/addressList/addressList?state=1'
            });
        },

        totalFun: function (e) {
            //全选
            // this.total = !this.total; // for (let i = 0; i < this.data.list.length; i++) {
            // //   if (this.data.total) {
            // //     this.data.list[i].select = true
            // //   } else {
            // //     this.data.list[i].select = false
            // //   }
            // // }

            // this.list.map((v, k) => {
            //     if (this.total) {
            //         v.select = true;
            //         select_list.push(v.id);
            //     } else {
            //         v.select = false;
            //     }
            // });
            // this.setData({
            //     list: this.list,
            //     total: this.total
            // });
            // this.totalPriceFun();
			let total =0
			this.total = !this.total
			this.lableUrls.forEach(item => {
				if(this.total){
					item.url = "/static/images/choice_y.png"
					for (let i = 0;i<this.list.length;i++){
						total += this.list[i].price
					}
				} else {
					item.url = "/static/images/choice_n.png"
				}
			})
			this.totalPrice = total
        },

        totalPriceFun: function (e) {
            //计算总价
            var that = this;
            let product_price = 0;

            for (var i = 0; i < that.list.length; i++) {
                if (that.list[i].select) {
                    product_price = product_price + that.list[i].product_price * that.list[i].num;
                }
            }
               that.totalPrice= product_price.toFixed(2)
            // console.log(that.data.totalPrice)
        },

        editFun: function (e) {
            //编辑按钮
            var that = this;
            that.setData({
                isEdit: !that.isEdit
            });
        },

        labelFun: function (index,item) {
			if (this.lableUrls[index].url.indexOf("y") != -1){
				this.totalPrice -= item.price*item.num
				this.lableUrls[index].url = "/static/images/choice_n.png"
			} else {
				this.totalPrice += item.price*item.num

				this.lableUrls[index].url = "/static/images/choice_y.png"
			}
			console.log(this.lableUrls[index].url);
            // //单选
            // let that = this;
            // let num = 0;
            // select_list.push(e.currentTarget.dataset.id);

            // for (let i = 0; i < that.list.length; i++) {
            //     if (that.list[i].id == e.currentTarget.dataset.id) {
            //         if (!that.list[i].select) {
            //             that.list[i].select = true;
            //         } else {
            //             that.list[i].select = !that.list[i].select;
            //         }

            //         that.setData({
            //             list: that.list
            //         });
            //     }

            //     if (that.list[i].select) {
            //         num++;

            //         if (num == that.list.length) {
            //             that.setData({
            //                 total: true
            //             });
            //         } else {
            //             that.setData({
            //                 total: false
            //             });
            //         }
            //     }
            // }

            // this.totalPriceFun();
        },

        upNum: function (productID, num) {
			let userid=uni.getStorageSync("userid");
            // console.log(id, num)
            uni.request({
				url:"/api/user/shoppingCart/updateShoppingCart",
				method:"POST",
                    data: {
                        num: num,
						user_id:userid,
						product_id:productID
                    },
                    success: (res) => {
                        console.log('更新成功', res);
                    },
                    fail: (res) => {
                        console.log('更新失败', res);
                    }
                });
        },

        reduceFun: function (e) {
            //减少商品数量
            this.list.map((v, k) => {
                // console.log(v._id)
                // console.log(e.target.dataset.item._id)
                if (v.id == e.target.dataset.item.id) {
                    if (this.list[k].num > 1) {
                        // this.data.list[k].num--
                        this.upNum(e.target.dataset.item._id, --this.list[k].num);
                    } else {
                        uni.showToast({
                            title: '该宝贝不能再减少了哦~',
                            icon: 'none',
                            duration: 2000
                        });
                    }
                }
            });
            this.setData({
                list: this.list
            }); // console.log(this.data.list)
            // this.upNum(e.target.dataset.item._id,)
            // this.totalPrice()
        },

        plusFun: function (e) {
            //增加商品数量
            this.list.map((v, k) => {
                if (v.id == e.target.dataset.item.id) {
                    // var num = this.data.list[k].num++
                    this.upNum(e.target.dataset.item.id, ++this.list[k].num);
                }
            });
            this.setData({
                list: this.list
            });
        },

        delItemFun: function (id) {
			console.log(id);
			let userid=uni.getStorageSync("userid");
            //删除单商品
            // var id = e.target ? e.target.dataset.item.id : e.id; // console.log(id)

            // this.list.map((v, k) => {
            //     if (v.id == id) {
            //         this.list.splice(k, 1);
               uni.request({
               	url: "/api/user/shoppingCart/deleteShoppingCart",
				 method:"POST",
				 data:{
				 user_id:userid,
				 product_id:id
				 },
				success(res) {
                                console.log('删除成功', res);
                            },

                            fail(res) {
                                console.log('删除失败', res);
                            }
                        
               })  ;               
                // }
            // });
            
               this.list=this.list
			  
        },

        addSelect: function (e) {
            for (var i = 0; i < select_list.length; i++) {
                this.list.map((v, k) => {
                    if (v.id == select_list[i]) {
                        uni.request({
							url:"/api/user/order/addOrder",
							method:"POST",
							data: {
                                user_id  : v.userid,
                                // _openid: v._openid,
                                product_picture: v.product_picture,
                                num: v.num,
                                product_price: v.product_price,
                                product_name: v.product_name,
                                address: this.addressDetail,
                                mobilePhone: this.mobilePhone,
                                username: this.userName
                            },
                        	
                            success(res) {
                                console.log('添加成功', res);
                            },

                            fail(res) {
                                console.log('添加失败', res);
                            }
                        });
                    }
                });
            }
        },

        deleteSelect: function (e) {
			let userid=uni.getStorageSync("userid");
            //删除选中商品函数
            // console.log(select_list.length)
            for (var i = 0; i < select_list.length; i++) {
             uni.request({
             	url: "/api/user/shoppingCart/deleteShoppingCart",
             				 method:"POST",
             				 data:{user_id:userid,
             				 product_id:select_list[i]
             				 },
                        success(res) {
                            console.log('删除成功', res);
                            select_list = [];
                        },

                        fail(res) {
                            console.log('删除失败', res);
                        }
                    });
					
            }
			// if()
			 // console.log(app.globalData.addressDetail);
			
			
        },

        closeFun: function (list) {
			console.log(list);

            //结算
			let that=this;
		
            if (that.totalPrice == 0) {
            	uni.showToast({
            		title: '请选择要结算的商品',
            		icon: 'none'
            	})
            } else {
            	uni.showModal({
            		title: '提示',
            		content: '您确定要支付吗？',
            		success: function(res) {
            			if (res.confirm) {
							
							
            				console.log('用户点击确定');
            				uni.navigateTo({
            					url:"/pages/orderPay/orderPay"
            				})
            			} else if (res.cancel) {
            				console.log('用户点击取消');
            			}
            
            
            		}
            	})
            }
			
        },

        delFun: function (e) {
            //删除选中商品
            var list = [];
            this.deleteSelect(); // console.log(select_list)

            this.list.map((v, k) => {
                if (!v.select) {
                    list.push(v);
                }
            });
            this.setData({
                list: list
            });
        }
    }
};
</script>
<style>
.top {
    display: flex;
    line-height: 44px;
    border-top: 1px solid #ededed;
    border-bottom: 1px solid #ededed;
    font-size: 14px;
    padding: 0 16px;
    align-items: center;
}

.top .city {
    padding-left: 30px;
    color: #999;
}

.top .edit-btn {
    color: #6ea1f5;
    flex-grow: 1;
    display: flex;
    justify-content: flex-end;
}

.label {
    width: 20px;
    height: 20px;
}

.label image {
    display: block;
    width: 20px;
    height: 20px;
}

.list .item {
    display: flex;
    border-bottom: 1px solid #ededed;
    padding: 0 16px;
    height: 118px;
    align-items: center;
}

.list .label {
    flex: 0 0 auto;
    padding: 10px 0;
}

.list .content {
    flex-grow: 1;
    display: flex;
}

.list .content image {
    flex: 0 0 auto;
    height: 94px;
    width: 94px;
    padding: 10px;
}

.list .content .text {
    flex-grow: 1;
    font-size: 14px;
}

.list .content .title {
    height: 44px;
    overflow: hidden;
}

.list .content .spec {
    font-size: 12px;
    color: #333333;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    line-height: 24px;
    max-height: 24px;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
}

.list .content .price {
    display: flex;
    font-size: 14px;
    padding-top: 10px;
}

.list .content .price text:nth-child(1) {
    color: red;
    flex: 1 0 50%;
}

.list .content .price text:nth-child(2) {
    color: #999999;
    flex: 1 0 50%;
    text-align: right;
}

.bottom {
    display: flex;
    font-size: 14px;
}

.bottom .left {
    display: flex;
    flex: 1 0 70%;
    align-items: center;
}

.bottom .left .text {
    display: flex;
    flex: 0 0 50%;
}

.bottom .left .total-price {
    flex: 0 0 50%;
    color: #333333;
    text-align: right;
}

.bottom .right {
    flex: 1 0 30%;
    background: red;
    font-size: 17px;
    color: #ffffff;
    text-align: center;
    line-height: 10vh;
}

.edit {
    padding-right: 0px !important;
}
.edit .content {
    width: 80%;
}
.edit .title {
    display: flex;
    width: 70%;
    line-height: 32px;
    text-align: center;
    border: 1px solid #d5d5d5;
    height: 32px !important;
    margin: 5px 0;
}

.edit .title input {
    flex: 1 0 33.333%;
    border-left: 1px solid #d5d5d5;
    border-right: 1px solid #d5d5d5;
    height: 32px;
}

.edit .title text {
    flex: 1 0 33.333%;
    height: 32px;
    font-size: 18px;
}

.edit .del-btn {
    margin-right: 0px;
    line-height: 119px;
    width: 65px;
    background: red;
    font-size: 14px;
    color: #fff;
    text-align: center;
}

.prohibit {
    background: #e5e5e5 !important;
}
</style>
